const Service = require('egg').Service;
const axios = require('axios');

class PaypalService extends Service {
  // Get PayPal access token
  async getAccessToken() {
    const { clientId, clientSecret } = this.app.config.paypal;
    const auth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

    try {
      const { data } = await axios({
        method: 'POST',
        url: 'https://api-m.sandbox.paypal.com/v1/oauth2/token',
        headers: {
          'Accept': 'application/json',
          'Authorization': `Basic ${auth}`,
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: 'grant_type=client_credentials'
      });

      return data.access_token;
    } catch (error) {
      console.log('PayPal Get Access Token Error:', error.response?.data || error.message);
      this.ctx.logger.error('PayPal Get Access Token Error:', error.response?.data || error);
      throw error;
    }
  }

  // Create PayPal order
  async createOrder(orderData) {
    try {
      const accessToken = await this.getAccessToken();

      const { data } = await axios({
        method: 'POST',
        url: 'https://api-m.sandbox.paypal.com/v2/checkout/orders',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`,
          'PayPal-Request-Id': `order_${orderData.orderId}_${Date.now()}`
        },
        data: {
          intent: 'CAPTURE',
          purchase_units: [{
            amount: {
              currency_code: 'AUD',
              value: orderData.amount.toString()
            },
            reference_id: orderData.orderId,
            description: orderData.description || 'Offshore Angling Booking'
          }],
          application_context: {
            return_url: `${this.app.config.antom.clientUrl}/#/payment/success?orderId=${orderData.orderId}`,
            cancel_url: `${this.app.config.antom.clientUrl}/#/payment/payment?type=cancel&orderId=${orderData.orderId}`,
            brand_name: 'Offshore Angling',
            locale: 'en-AU',
            landing_page: 'LOGIN',
            user_action: 'PAY_NOW',
            shipping_preference: 'NO_SHIPPING'
          }
        }
      });

      console.log('PayPal Create Order Response:', data);
      return {
        success: true,
        data
      };
    } catch (error) {
      console.log('PayPal Create Order Error:', error.response?.data || error.message);
      this.ctx.logger.error('PayPal Create Order Error:', error.response?.data || error);
      return {
        success: false,
        error: error.response?.data?.message || error.message
      };
    }
  }

  // Capture payment
  async capturePayment(paypalOrderId) {
    try {
      const accessToken = await this.getAccessToken();

      const { data } = await axios({
        method: 'POST',
        url: `https://api-m.sandbox.paypal.com/v2/checkout/orders/${paypalOrderId}/capture`,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`,
          'PayPal-Request-Id': `capture_${paypalOrderId}_${Date.now()}`
        }
      });
      console.log('首款数据',data)
      return {
        success: true,
        data
      };
    } catch (error) {
      console.log('PayPal Capture Payment Error:', error.response?.data || error.message);
      this.ctx.logger.error('PayPal Capture Payment Error:', error.response?.data || error);
      return {
        success: false,
        error: error.response?.data?.message || error.message
      };
    }
  }

  // Verify payment status
  async verifyPayment(paypalOrderId) {
    try {
      const accessToken = await this.getAccessToken();

      const { data } = await axios({
        method: 'GET',
        url: `https://api-m.sandbox.paypal.com/v2/checkout/orders/${paypalOrderId}`,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`,
        }
      });

      return {
        success: true,
        data: {
          status: data.status,
          orderId: data.purchase_units[0].reference_id,
          paypalOrderId: data.id,
          amount: data.purchase_units[0].amount
        }
      };
    } catch (error) {
      console.log('PayPal Verify Payment Error:', error.response?.data || error.message);
      this.ctx.logger.error('PayPal Verify Payment Error:', error.response?.data || error);
      return {
        success: false,
        error: error.response?.data?.message || error.message
      };
    }
  }

  // Refund payment
  async refundPayment(captureId, refundData) {
    try {
      const accessToken = await this.getAccessToken();

      const { data } = await axios({
        method: 'POST',
        url: `https://api-m.sandbox.paypal.com/v2/payments/captures/${captureId}/refund`,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${accessToken}`,
          'PayPal-Request-Id': `refund_${captureId}_${Date.now()}`,
          'Prefer': 'return=representation'
        },
        data: {
          amount: {
            value: refundData.amount.toString(),
            currency_code: 'AUD'
          },
          note_to_payer: refundData.note || 'Refund for order',
          invoice_id: refundData.orderId
        }
      });

      return {
        success: true,
        data
      };
    } catch (error) {
      console.log('PayPal Refund Error:', error.response?.data || error.message);
      this.ctx.logger.error('PayPal Refund Error:', error.response?.data || error);
      return {
        success: false,
        error: error.response?.data?.message || error.message
      };
    }
  }
}

module.exports = PaypalService;
